var jsFragments = {
  fragments: null,

  testCase: function(){
    this.init("http://www.rfc-editor.org/rfc/rfc1123.txt");
    this.getFragmentsByViewpoint("http://argos.local.hypertopic.org/viewpoint/5/");

  },

  getFragmentsByViewpoint: function(url){
    if(url == null) return null;
    if(this.fragments == null || this.fragments.length == 0) return null;
    var result = new Array();
    for(var i = 0;i < this.fragments.length; i++){
      var fragment = this.fragments[i];
      for(var j = 0;j < fragment.viewpoints.length;j++){
        if(url == fragment.viewpoints[j])
          result.push(fragment);
      }
    }
    var_dump("[fragment.js::getFragmentsByViewpoint]",result,1);
    return result;
  },

  getFragments: function(){
    var_dump("[fragment.js::getFragments]",this.fragments,1);
    return this.fragments;
  },

  init: function(uri){
    var currentUri = uri;
    if(currentUri == null) currentUri = getCurrentUri();

    if(typeof(currentUri) != "string" || currentUri.trim() == "" || (currentUri.substring(0, "about:".length) == "about:"))
      return false;

    this.fragments = new Array();
    var setting = getCurrentSetting();
    var requestUri = setting.hypertopic.url + "entity/" + encodeURIComponent(currentUri) + "/";

    var entity = new Entity();
    entity.uri = requestUri;
    entity = entity.httpGet(setting.hypertopic.username, setting.hypertopic.password);
    if(entity == false)
      return false;


    var regex = /\/([0-9]+)\+([0-9]+)\/?$/;
    for(var i = 0;i < entity.relatedEntities.length; i++){
      var tmpFragment = {};
      var uri = entity.relatedEntities[i].href;
      if(!regex.test(uri)) continue;
      var res = uri.match(regex);
      try{
        tmpFragment.startPos = parseInt(res[1]);
        tmpFragment.endPos = parseInt(res[2]);
      } catch(ex) {continue;}
      if(tmpFragment.startPos > tmpFragment.endPos){
  			var temp = tmpFragment.startPos;
  			tmpFragment.startPos = tmpFragment.endPos;
  			tmpFragment.endPos = temp;
  		}

      //get fragment entity detail
      var tmpEntity = new Entity();
      tmpEntity.uri = uri;
      tmpEntity = tmpEntity.httpGet(setting.hypertopic.username, setting.hypertopic.password);
      if(tmpEntity == false) continue;

      for(var j = 0; j < tmpEntity.attributes.length; j++){
        var attribute = tmpEntity.attributes[j];
        if(attribute.name=="type" && attribute.value=="fragment")
          tmpFragment.isFragment = true;
        if(attribute.name=="name")
          tmpFragment.content = attribute.value;
        if(attribute.name=="colorIndex"){
          tmpFragment.colorIndex = parseInt(attribute.value);
          if(tmpFragment.colorIndex == "NaN")
            tmpFragment.colorIndex = 0;
        }
      }

      var viewpointList = new Array();
      for( var j = 0; j < tmpEntity.topics.length; j++){
        var href = tmpEntity.topics[j].href;
        if(href != "")
          href = href.substr(0, href.indexOf("/topic/")+1);
        viewpointList.push(href);
      }
      viewpointList = viewpointList.unique(true);
      var_dump("[highlighter.js::init] viewpointList:" , viewpointList, 1);
      tmpFragment.viewpoints = viewpointList;
      tmpFragment.topics = tmpEntity.topics;
      if(tmpFragment.isFragment == true)
        this.fragments.push(tmpFragment);
    }
    this.fragments.sortNum();
  },

  getColorTopic: function(colorIndex, viewpointUri){
    var stringBundle = document.getElementById("sbLasuli");

    var colorTopicUri = null;
    if(colorIndex == null) colorIndex = 0;
    var topicName = stringBundle.getString("color." + colorIndex + ".name");

    if(viewpointUri == null) return null;
    debug("[fragments.js::getColorTopic] getColorTopic viewpoint url:" + viewpointUri, 4);
    debug("[fragments.js::getColorTopic] getColorTopic colorIndex:" + colorIndex, 4);
    var setting = getCurrentSetting();
    var entityObject = new Entity();
    entityObject.uri = setting.hypertopic.url + COLORENTITY_PREFIX + colorIndex + "/";
    debug("[fragments.js::getColorTopic] entityObject.href:" + entityObject.uri, 4);
    var res = entityObject.httpGet(setting.hypertopic.username, setting.hypertopic.password);

    if(res == false){
      entityObject.addAttribute("name","color index entity");
      debug("[fragment.js::getColorTopic] create color entity:" + entityObject.uri, 4);
      res = entityObject.httpPut(setting.hypertopic.username, setting.hypertopic.password);
      if(res == false){
        debug("[fragment.js::getColorTopic] unable to create color index entity", 4);
        return null;
      }
    }
    else
      entityObject = res;
    var_dump("[fragment.js::getColorTopic]",entityObject,4);
    for(var i=0; i < entityObject.topics.length; i++){
      colorTopicUri = entityObject.topics[i].href + "";
      if(colorTopicUri.startsWith(viewpointUri))
        return colorTopicUri;
    }

  	var tmpEntity = {};
  	tmpEntity.name = "colorIndex";
  	tmpEntity.href = setting.hypertopic.url + COLORENTITY_PREFIX + colorIndex + "/";
  	var topic = new Topic();
  	topic.entities.push(tmpEntity);

    topic.name = topicName;
    topic.viewpoint.href = viewpointUri;

  	topic.href = topic.httpPost(viewpointUri + "topic/", setting.hypertopic.username, setting.hypertopic.password);
  	if(topic.href == null){
  	  var_dump("[fragments.js::getColorTopic] create color topic failed:",topic, 4);
  	  return null;
  	}
  	return topic.href;
  },

  addFragment: function(fragment, viewpointUri){
    var colorTopicUri = this.getColorTopic(fragment.colorIndex, viewpointUri);
    var_dump("[fragments.js::addFragment] colorTopicUri:", colorTopicUri, 4);
    var currentUri = getCurrentUri();
    //if(currentUri.indexOf("#") > 0)
    //  currentUri = currentUri.substring(0,currentUri.indexOf("#"));
    var setting = getCurrentSetting();
		var requestUri = setting.hypertopic.url + "entity/" + encodeURIComponent(currentUri) + "/" + fragment.startPos + "+" + fragment.endPos;
    var entity = new Entity();
    entity.uri = requestUri;

    entity.addAttribute("name",fragment.content);
		entity.addAttribute("type","fragment");
		entity.addAttribute("colorIndex",fragment.colorIndex);
		entity.addResource("highlight", HIGHLIGHT_PHPSCRIPT + currentUri);
		entity.addResource("fragment", FRAGMENT_PHPSCRIPT + currentUri);
		entity.addResource("source", getCurrentUri());

		if(colorTopicUri != null)
		  entity.addTopic("colorIndexTopic", colorTopicUri);
    var_dump("[fragments.js::addFragment] entity:", entity, 4);
    var res = entity.httpPut(setting.hypertopic.username, setting.hypertopic.password);
    if(!res) return false;

  },

  deleteFragment: function(fragment){
    var stringBundle = document.getElementById("sbLasuli");
    var setting = getCurrentSetting();
    var currentUri = getCurrentUri();
		var requestUri = setting.hypertopic.url + "entity/" + encodeURIComponent(currentUri) + "/" + fragment.startPos + "+" + fragment.endPos;
    var entity = new Entity();
    entity.uri = requestUri;
    var res = entity.httpDelete(setting.hypertopic.username, setting.hypertopic.password);
    if(!res){
      alert(stringBundle.getString("fragment.delete.failed"));
      return;
    }
  },

  updateFragmentColor: function(fragment,colorIndex){
    var stringBundle = document.getElementById("sbLasuli");
    var setting = getCurrentSetting();
		var currentUri = getCurrentUri();
    if(currentUri == null) return;
		var requestUri = setting.hypertopic.url + "entity/" + encodeURIComponent(currentUri) + "/" + fragment.startPos + "+" + fragment.endPos;
    var viewpointUri = sidebarGui.getSelectedPanelViewpointUri();
    if(viewpointUri == null) return;
    var colorTopic = null;
    var originalColorTopic = null;
    colorTopic = this.getColorTopic(colorIndex, viewpointUri);
    originalColorTopic = this.getColorTopic(fragment.colorIndex, viewpointUri);
    var_dump("[fragment.js::updateFragment] colorTopicUri:",colorTopic, 4);
    var_dump("[fragment.js::updateFragment] originalColorTopicUri:",originalColorTopic, 4);

    var entity = new Entity();
    entity.uri = requestUri;
    entity = entity.httpGet(setting.hypertopic.username, setting.hypertopic.password);
    if(entity == false) return;
      entity.uri = requestUri;

    debug("[fragments.js::updateFragmentColor] request URL:" + entity.uri, 4);

    for(var i = 0; i < entity.attributes.length; i++){
      if(entity.attributes[i].name == "colorIndex")
        entity.attributes[i].value = colorIndex;
    }
    if(colorTopic != null){
		  entity.addTopic("color", colorTopic);
		  entity.removeTopic(originalColorTopic);
		}
    var res = entity.httpPut(setting.hypertopic.username, setting.hypertopic.password);
    if(!res){
      alert(stringBundle.getString("fragment.put.failed"));
      return;
    }
    //TODO reload fragments
  },

  getRelatedTopics: function(uri){
    var currentUri = uri;
    if(currentUri == null) currentUri = getCurrentUri();

    if(typeof(currentUri) != "string" || currentUri.trim() == "" || (currentUri.substring(0, "about:".length) == "about:"))
      return false;

    var setting = getCurrentSetting();
    var requestUrl = setting.hypertopic.url + "resource/" + encodeURIComponent(currentUri);
    var resource = new Resource();
    resource.uri = requestUrl;
    resource.href = currentUri;
    var resource = resource.httpGet(setting.hypertopic.username, setting.hypertopic.password);
    if(resource == false)
      return false;

    var topics = new Array();
    for(var i = 0;i < resource.entities.length; i++){
      var entity = new Entity();
      entity.uri = resource.entities[i].href;
      entity = entity.httpGet(setting.hypertopic.username, setting.hypertopic.password);
      if(entity == false) continue;

      for(var j = 0;j < entity.topics.length; j++){
        var href = entity.topics[j].href;
        topics.push(href);
      }
      topics = topics.unique(true);
    }
    return topics;
  }
}